package com.fa4j.system.settings.controller;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.Page;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.system.login.util.LoginUtil;
import com.fa4j.system.settings.convert.SettingsConverter;
import com.fa4j.system.settings.model.*;
import com.fa4j.system.settings.repository.SettingsRepository;
import com.fa4j.system.settings.service.SettingsService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("system/settings")
@RequiredArgsConstructor
public class SettingsController {

    private final SettingsService settingsService;
    private final SettingsRepository settingsRepository;

    private final SettingsConverter settingsConverter;

    @ApiMethod(name = "系统设置-分页查询", type = AppType.MANAGE)
    @GetMapping("page")
    public Page<Settings> page(SettingsQuery query) {
        return settingsRepository.queryPage(query);
    }

    @ApiMethod(name = "系统设置-详情查询", type = AppType.MANAGE)
    @GetMapping("{id}")
    public Settings detail(@PathVariable Integer id) {
        return settingsRepository.findById(id)
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统设置"));
    }

    @ApiMethod(name = "系统设置-创建", type = AppType.MANAGE)

    @PostMapping
    public Settings create(@Valid @RequestBody SettingsCreateCmd cmd) {
        return settingsService.create(cmd);
    }

    @ApiMethod(name = "系统设置-编辑", type = AppType.MANAGE)
    @PatchMapping
    public Settings modify(@Valid @RequestBody SettingsModifyCmd cmd) {
        return settingsService.modify(cmd);
    }

    @ApiMethod(name = "系统设置-数据编辑", type = AppType.MANAGE)
    @PutMapping("data")
    public Settings modifyData(@Valid @RequestBody SettingsDataModifyCmd cmd) {
        return settingsService.modify(settingsConverter.toModifyCmd(cmd));
    }

    @ApiMethod(name = "系统设置-删除", type = AppType.MANAGE)
    @DeleteMapping("{id}")
    public Settings remove(@PathVariable Integer id) {
        return settingsService.remove(RemoveCmd.of(id, LoginUtil.getAccountId()));
    }

}
